package day17;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
//基于Lock锁实现购票功能
public class Demo6 {
    int sum=100;
    ReentrantLock lock=new ReentrantLock();
    public void buy(){
        String name=Thread.currentThread().getName();
        //手动加锁:如果锁一直竞争不到，会一直等待
        //lock.lock();
        //tryLock():尝试获取锁，如果获取不到，直接放弃
        //tryLock(时间，单位)：尝试获取锁的时间，如果时间到了还获取不到，则不要了
        try {
            if (lock.tryLock(1, TimeUnit.SECONDS)){
                try {
                    if (sum>0){
                        sum--;
                        Thread.sleep(100);
                        System.out.println(name+"购买成功，剩余："+sum);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }else {
                System.out.println(name+"买不到，放弃了");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //手动释放锁:适合放在finally编写

    }

    public static void main(String[] args) {
        Demo6 d=new Demo6();
        new Thread(()->{
            for (int i=0;i<100;i++){
                d.buy();
            }
        },"张三").start();
        new Thread(()->{
            for (int i=0;i<100;i++){
                d.buy();
            }
        },"李四").start();
    }

}
